public class Test {
    public static void main(String[] args) {
        //1.创建一个数组来储存对象
        Student[] arr = new Student[3];
        //2.创建学生对象并添加到数组当中
        Student stu1 = new Student(1, "zhangsan", 23);
        Student stu2 = new Student(2, "lisi", 24);
        Student stu3 = new Student(3, "wangwu", 25);
        //4.把学生对象添加到数组当中
        arr[0] = stu1;
        arr[1] = stu2;
        arr[2] = stu3;
        //要求1：再次添加一个学生对象，并在添加的时候进行学号的唯一验证
        Student stu4 = new Student(4, "zhaoliu", 26);
        //唯一性的判断
        //已存在--不用添加
        //不存在--添加到数组
        boolean flag = contains(arr, stu4.getId());
        if (flag) {
            System.out.println("当前id重复，请修改id后再进行添加");
        } else {
            int count = getCount(arr);
            if (count == arr.length) {
                //已经存满
                Student[] newArr = creatNewArr(arr);
                newArr[count] = stu4;
            } else {
                arr[count] = stu4;
                printArr(arr);
            }
        }
    }
        public static void printArr(Student[] arr) {
            for (int i = 0; i < arr.length; i++) {
                Student stu = arr[i];
                if (stu != null) {
                    System.out.println(stu.getId() + "," + stu.getName() + "," + stu.getAge());
                }
            }
        }
        //创建一个新数组，长度=老数组+1
        //拷贝
        public static Student[] creatNewArr(Student[]arr){
            Student[] newArr = new Student[arr.length + 1];
            //循环得到老数组的每一个元素
            for (int i = 0; i < arr.length; i++) {
                newArr[i] = arr[i];
            }
            return newArr;
        }
        //定义一个方法判断数组中已经存了几个元素
        public static int getCount(Student[]arr){
            int count = 0;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] != null) {
                    count++;
                }
                return count;
            }
            return 0;
            //当循环结束之后，我就知道了数组中一共有几个元素

        }
        public static boolean contains(Student[]arr,int id){
            for (int i = 0; i < arr.length; i++) {
                //依次获取数组里面的每一个学生对象
                Student stu = arr[i];
                if (stu != null) {
                    //依次获取学生对象的id
                    int sid = stu.getId();
                    if (sid == id) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

